package com.sunshine.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传测试
 *
 * @author WeiHong
 * @date 2018/8/13
 */
@RestController
@RequestMapping("file")
public class FileController {

    private static final String filePath = "D://upload/";

    @PostMapping("upload")
    public JSONObject upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        JSONObject result = new JSONObject();
        // 姓名
        String name = request.getParameter("name");
        // 文件名
        String fileName = file.getOriginalFilename();
        // 文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重新生成唯一文件名，用于存储数据库
        String newFileName = UUID.randomUUID().toString() + suffixName;
        //创建文件
        File dest = new File(filePath + newFileName);
        File parentFile = dest.getParentFile();
        if (!parentFile.exists()){
            parentFile.mkdirs();
        }
        Map map = new HashMap(2);
        map.put("filePath", dest.getAbsolutePath());
        map.put("name", name);
        try {
            file.transferTo(dest);
            result.put("success", true);
            result.put("data", map);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (JSONObject) result.put("success", false);
    }

}
